﻿using System;
using System.Threading;
namespace X.Async
{
    public class XAsyncResult : IAsyncResult
    {
        #region IAsyncResult Members

        private object m_asyncState;
        public object AsyncState
        {
            get { return m_asyncState; }
            set { m_asyncState = value; }
        }

        private ManualResetEvent m_asyncWaitHandle = new ManualResetEvent(false);
        public WaitHandle AsyncWaitHandle
        {
            get { return m_asyncWaitHandle; }
        }

        public bool CompletedSynchronously
        {
            get { return false; }
        }

        private long m_isCompleted = 0;
        public bool IsCompleted
        {
            get
            {
                return Interlocked.Read(ref m_isCompleted) != 0;
            }
            set
            {
                if (Interlocked.Exchange(ref m_isCompleted, value ? 1 : 0) == 0 &&
                    value)
                {
                    m_asyncWaitHandle.Set();
                }
            }
        }
        #endregion
    }
}